import { useState, useEffect, useRef, useCallback } from 'react'
import { Button } from '@/components/ui/button'

export default function ScreenRegionSelector() {
  const [isSelecting, setIsSelecting] = useState(false)
  const [startPoint, setStartPoint] = useState<{ x: number; y: number } | null>(null)
  const [currentPoint, setCurrentPoint] = useState<{ x: number; y: number } | null>(null)
  const [selectedRegion, setSelectedRegion] = useState<{ x: number; y: number; width: number; height: number } | null>(null)
  const [isConfirming, setIsConfirming] = useState(false)
  const overlayRef = useRef<HTMLDivElement>(null)

  // 处理鼠标按下事件
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (e.button !== 0 || isConfirming) return // 只处理左键，确认中时不允许选择
    
    const x = e.clientX
    const y = e.clientY
    
    setStartPoint({ x, y })
    setCurrentPoint({ x, y })
    setIsSelecting(true)
    setSelectedRegion(null)
  }, [isConfirming])

  // 处理鼠标移动事件
  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    if (!isSelecting || !startPoint) return
    
    const x = e.clientX
    const y = e.clientY
    
    setCurrentPoint({ x, y })
  }, [isSelecting, startPoint])

  // 处理鼠标抬起事件
  const handleMouseUp = useCallback(() => {
    if (!isSelecting || !startPoint || !currentPoint) {
      setIsSelecting(false)
      setStartPoint(null)
      setCurrentPoint(null)
      return
    }

    const region = {
      x: Math.min(startPoint.x, currentPoint.x),
      y: Math.min(startPoint.y, currentPoint.y),
      width: Math.abs(currentPoint.x - startPoint.x),
      height: Math.abs(currentPoint.y - startPoint.y),
    }

    // 确保选择的区域有一定大小
    if (region.width > 10 && region.height > 10) {
      console.log('[屏幕区域选择] 选择区域:', region)
      setSelectedRegion(region)
    }
    
    setIsSelecting(false)
    setStartPoint(null)
    setCurrentPoint(null)
  }, [isSelecting, startPoint, currentPoint])

  // 计算选择框的样式
  const getSelectionStyle = () => {
    if (selectedRegion) {
      return {
        left: selectedRegion.x,
        top: selectedRegion.y,
        width: selectedRegion.width,
        height: selectedRegion.height,
      }
    }
    
    if (!startPoint || !currentPoint) return { display: 'none' }
    
    return {
      left: Math.min(startPoint.x, currentPoint.x),
      top: Math.min(startPoint.y, currentPoint.y),
      width: Math.abs(currentPoint.x - startPoint.x),
      height: Math.abs(currentPoint.y - startPoint.y),
    }
  }

  // 确认选择
  const handleConfirm = () => {
    if (!selectedRegion) {
      console.warn('[屏幕区域选择] 没有选择区域')
      return
    }
    
    console.log('[屏幕区域选择] 确认选择区域 (CSS坐标):', selectedRegion)
    
    // 🔧 转换坐标：CSS像素 -> 物理像素（适配高DPI显示器）
    const devicePixelRatio = window.devicePixelRatio || 1
    console.log('[屏幕区域选择] 设备像素比:', devicePixelRatio)
    
    const physicalRegion = {
      x: Math.round(selectedRegion.x * devicePixelRatio),
      y: Math.round(selectedRegion.y * devicePixelRatio),
      width: Math.round(selectedRegion.width * devicePixelRatio),
      height: Math.round(selectedRegion.height * devicePixelRatio),
    }
    
    console.log('[屏幕区域选择] 转换后的物理坐标:', physicalRegion)
    setIsConfirming(true)
    
    // 发送物理坐标结果
    if (window.ipcRenderer) {
      try {
        window.ipcRenderer.send('screen-region-selector:result' as any, physicalRegion)
        console.log('[屏幕区域选择] 物理坐标已发送via IPC:', physicalRegion)
      } catch (error) {
        console.error('[屏幕区域选择] IPC发送失败:', error)
      }
    } else {
      console.error('[屏幕区域选择] IPC不可用，无法发送结果')
    }
    
    // 尝试多种方式关闭窗口
    const closeWindow = () => {
      console.log('[屏幕区域选择] 开始关闭窗口...')
      
      // 方式1: 使用 window.close()
      try {
        if (window.close) {
          window.close()
          console.log('[屏幕区域选择] 已调用 window.close()')
        } else {
          console.warn('[屏幕区域选择] window.close 不可用')
        }
      } catch (closeError) {
        console.error('[屏幕区域选择] window.close() 失败:', closeError)
      }
      
      // 方式2: 通过 IPC 请求关闭（备用方案）
      if (window.ipcRenderer) {
        try {
          // @ts-ignore
          window.ipcRenderer.send('window:request-close')
        } catch (ipcError) {
          console.error('[屏幕区域选择] IPC关闭请求失败:', ipcError)
        }
      }
    }
    
    // 延迟关闭，确保用户能看到确认提示
    setTimeout(closeWindow, 800) // 稍微延长一点时间让用户看到选择成功的反馈
  }

  // 取消选择
  const handleCancel = () => {
    console.log('[屏幕区域选择] 取消选择')
    if (window.ipcRenderer) {
      window.ipcRenderer.send('screen-region-selector:cancel' as any)
    }
  }

  // 重新选择
  const handleReselect = () => {
    setSelectedRegion(null)
    setStartPoint(null)
    setCurrentPoint(null)
    setIsSelecting(false)
  }

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        handleCancel() // ESC 总是可以取消
      } else if (e.key === 'Enter' && selectedRegion && !isConfirming) {
        handleConfirm() // 只有未确认时才允许 Enter
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [selectedRegion, isConfirming])

  // 设置页面背景透明
  useEffect(() => {
    // 设置 body 背景透明
    const originalBodyStyle = document.body.style.backgroundColor
    const originalHtmlStyle = document.documentElement.style.backgroundColor
    
    document.body.style.backgroundColor = 'transparent'
    document.documentElement.style.backgroundColor = 'transparent'
    
    return () => {
      // 恢复原始样式
      document.body.style.backgroundColor = originalBodyStyle
      document.documentElement.style.backgroundColor = originalHtmlStyle
    }
  }, [])

  // 阻止右键菜单
  useEffect(() => {
    const handleContextMenu = (e: Event) => {
      e.preventDefault()
    }

    window.addEventListener('contextmenu', handleContextMenu)
    return () => window.removeEventListener('contextmenu', handleContextMenu)
  }, [])

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 cursor-crosshair select-none bg-transparent"
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
    >
      {/* 选择框 - 确认中时隐藏 */}
      {!isConfirming && (
        <div
          className="absolute border-2 border-blue-500 bg-blue-500/20 pointer-events-none"
          style={getSelectionStyle()}
        >
          {selectedRegion && (
            <div className="absolute -top-16 left-0 bg-blue-500 text-white px-3 py-2 text-xs rounded-lg shadow-lg">
              <div className="font-semibold mb-1">
                {selectedRegion.width} × {selectedRegion.height}
              </div>
              <div className="opacity-90">
                坐标: ({selectedRegion.x}, {selectedRegion.y})
              </div>
            </div>
          )}
        </div>
      )}

      {/* 提示文字 - 只在没有选择时显示 */}
      {!selectedRegion && !isSelecting && !isConfirming && (
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-white text-center bg-black/90 backdrop-blur-sm p-6 rounded-lg pointer-events-none border border-white/20 shadow-2xl">
          <h3 className="text-xl font-semibold mb-3">拖拽选择监控区域</h3>
          <p className="text-sm opacity-90 mb-2">按住鼠标左键拖拽选择区域</p>
          <p className="text-xs opacity-70">按 ESC 取消 | 按 Enter 确认</p>
        </div>
      )}

      {/* 确认中提示 */}
      {isConfirming && (
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-white text-center bg-green-600/90 backdrop-blur-sm p-6 rounded-lg pointer-events-none border border-green-400/40 shadow-2xl">
          <div className="flex items-center justify-center mb-3">
            <div className="mr-3 h-6 w-6 animate-spin rounded-full border-2 border-white border-t-transparent" />
            <h3 className="text-xl font-semibold">选择成功！</h3>
          </div>
          <div className="space-y-1 text-sm opacity-90">
            <p>尺寸: {selectedRegion?.width} × {selectedRegion?.height}</p>
            <p>坐标: ({selectedRegion?.x}, {selectedRegion?.y})</p>
            <p className="text-xs mt-2 opacity-70">窗口即将关闭...</p>
          </div>
        </div>
      )}

      {/* 控制按钮 - 只在选择了区域且未确认时显示 */}
      
      {selectedRegion && !isConfirming && (
        <div 
          className="absolute bottom-6 left-1/2 transform -translate-x-1/2 flex gap-3 bg-black/90 backdrop-blur-sm p-4 rounded-lg border border-white/20 shadow-2xl pointer-events-auto"
          onMouseDown={(e) => e.stopPropagation()}
          onMouseUp={(e) => e.stopPropagation()}
          onMouseMove={(e) => e.stopPropagation()}
        >
          <Button
            onClick={(e) => {
              e.stopPropagation()
              handleReselect()
            }}
            variant="outline"
            size="sm"
            className="!text-white !border-white hover:!bg-white hover:!text-black bg-transparent"
          >
            重新选择
          </Button>
          <Button
            onClick={(e) => {
              e.stopPropagation()
              handleCancel()
            }}
            variant="destructive"
            size="sm"
          >
            取消
          </Button>
          <Button
            onClick={(e) => {
              e.stopPropagation()
              handleConfirm()
            }}
            variant="default"
            size="sm"
            className="bg-blue-600 hover:bg-blue-700"
          >
            确认选择
          </Button>
        </div>
      )}

      {/* 右上角取消按钮 - 确认中时隐藏 */}
      {!isConfirming && (
        <div 
          className="absolute top-4 right-4 pointer-events-auto"
          onMouseDown={(e) => e.stopPropagation()}
          onMouseUp={(e) => e.stopPropagation()}
          onMouseMove={(e) => e.stopPropagation()}
        >
          <Button
            onClick={(e) => {
              e.stopPropagation()
              handleCancel()
            }}
            variant="destructive"
            size="sm"
            className="backdrop-blur-sm shadow-lg"
          >
            × 取消选择
          </Button>
        </div>
      )}
    </div>
  )
}
